﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.AwesomeMvc;
using Omu.ProDinner.Core.Model;
using Omu.ProDinner.Core.Repository;
using Omu.ProDinner.WebUI.Controllers.Awesome;

namespace Omu.ProDinner.WebUI.Controllers
{
    public class MealsMultiLookupController : Controller
    {
        private readonly IRepo<Meal> repo;

        public MealsMultiLookupController(IRepo<Meal> repo)
        {
            this.repo = repo;
        }

        [HttpPost]
        public ActionResult Search(string search, int[] selected, int page)
        {
            const int pageSize = 9;
            var list = repo.Where(o => o.Name.Contains(search)).OrderByDescending(o => o.Id)
                .Where(o => selected == null || !selected.Contains(o.Id));
            
            return Json(new AjaxListResult
                            {
                                Content = this.RenderView("ListItems/MealItem",list.Page(page, pageSize)),
                                More = list.Count() > page * pageSize
                            });
        }

        public ActionResult Selected(IEnumerable<int> selected)
        {
            var list = repo.GetAll()
                .Where(o => selected != null && selected.Contains(o.Id));

            return Json(new AjaxListResult
                         {
                             Content = this.RenderView("ListItems/MealItem", list)
                         });
        }

        public ActionResult GetItems(IEnumerable<int> v)
        {
            return Json(repo.GetAll().Where(o => v.Contains(o.Id)).Select(o => new KeyContent
            {
                Key = o.Id,
                Content = @"<img  src='" + Url.Content("~/pictures/Meals/" + Pic(o.Picture)) + "' class='mthumb' />" + o.Name,
                Encode = false
            }));
        }

        private static string Pic(string o)
        {
            return string.IsNullOrEmpty(o) ? "m0.jpg" : "m" + o;
        }

    }
}